# -*- coding: utf-8 -*-
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, Boolean

engine = create_engine('mysql+pymysql://用户名:密码@数据库ip地址:端口号/数据库名')
Base = declarative_base()


class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(String(40), nullable=True)
    password = Column(String(64), nullable=True)
    email = Column(String(64), nullable=False, index=True)
    # is_activate = Column(Boolean, default=True)

    def __repr__(self):
        return self.email


# 建立一个会话
Session = sessionmaker(bind=engine)
session = Session()
if __name__ == '__main__':
    # Base.metadata.create_all(engine)  # 创建模型对应的表
    # ------添加数据------
    user1 = User(username='测试名1', password='1234567', email='xxxxx@qq.com')
    session.add(user1)   # add_all()可以添加一个列表
    user2 = User(username='测试名2', password='asdfsdg', email='vvvvv@qq.com')
    session.add(user2)  # add_all()可以添加一个列表

    session.commit()
    # -----Read------
    # print(type(session.query(User).get(2)))
    # print(type(session.query(User).all()))
    # -----Update------
    # user1 = session.query(User).get(1)
    # user1.username = 'wsy'
    # session.add(user1)
    # session.commit()
    # -----Delete------
    # user = session.query(User).get(1)
    # session.delete(user)
    # session.commit()
